package com.achao.controller;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.Tracer;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: achao
 * @DateTime: 2022/10/16 10:22
 * @Description: TODO
 */
@Slf4j
@RestController
public class HelloController {

    private static final String RESOURCE_NAME = "hello";
    private static final String USER_RESOURCE_NAME = "user";
    private static final String DEGRADE_RESOURCE_NAME = "degrade";

    /**
     * 使用sentinel进行流控
     *
     * @return
     */
    @RequestMapping("/hello")
    public String hello() {

        Entry entry = null;
        try {
            // sentinel针对资源进行限制
            entry = SphU.entry(RESOURCE_NAME);
            // 被保护的逻辑
            String str = "hello World";
            log.info("======== ->{}",str);
            return str;
        }catch (BlockException blockException){
            // 资源访问阻止,限流或降级
            log.info("======== ->{}","block");
            return "被流控了";
        }catch (Exception exception){
            // 若需要配置降级,需要通过这种方式来记录业务异常
            Tracer.traceEntry(exception,entry);
        }finally {
            if (entry != null){
                entry.exit();
            }
        }
        return null;
    }

    /**
     * 定义规则
     */
    @PostConstruct
    private static void initFlowRules(){
        // 流控规则
        List<FlowRule> rules = new ArrayList<>();
        // 流控
        FlowRule rule = new FlowRule();
        // 设置受保护的资源
        rule.setRefResource(RESOURCE_NAME);
        // 设置流控规则 QPS
        rule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        // 设置受保护的资源阈值
        /*一秒内只能访问一次*/
        rule.setCount(1);
        rules.add(rule);

        // 加载配置好的规则
        FlowRuleManager.loadRules(rules);
        log.info("加载好配置了");
    }



}
